package com.zzzzzz.app.account.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.zzzzzz.app.account.NoSuchRoleException;
import com.zzzzzz.app.account.model.po.Role;
import com.zzzzzz.core.dao.BaseDao;
import com.zzzzzz.core.exception.SystemException;

@Repository
public class RoleDao extends BaseDao {

	private static final String ADD = "insert into role_(role_id, name, description) values(:roleId, :name, :description)";
	
	private static final String EDIT = "update role_ set name = :name, description = :description where role_id = :roleId";
	
	private static final String DELETE = "delete from role_ where role_id = ?";

	private static final String FIND_BY_ID = "select * from role_ where role_id = ?";

	private static final String FIND_ALL_COUNT = "select count(*) from role_";
	
	private static final String FIND_ALL_LIMIT = "SELECT * FROM role_ ORDER BY role_id DESC LIMIT ?, ?";

	private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No Role exists with the primary key ";	
	
	protected class RoleRowMapper implements RowMapper<Role> {
		public Role mapRow(ResultSet rs, int rn) throws SQLException {
			Role role = new Role();
			role.setRoleId(rs.getLong("role_id"));
			role.setName(rs.getString("name"));
			role.setDescription(rs.getString("description"));
			return role;
		}
	}
	
	public Role add(Role role) throws Exception {
		try{
			long roleId = updateForLongKey(ADD, role);
			role.setRoleId(roleId);
			return role;
		}catch (Exception e) {
			if(e instanceof DuplicateKeyException) {
				throw e;
			}else {
				throw processException(e);
			}
		}
	}
	
	public void edit(Role role) throws SystemException {
		update(EDIT, role);
	}
	
	public void delete(Long roleId) throws SystemException {
		try{
			update(DELETE, roleId);
		}catch (Exception e) {
			throw processException(e);
		}
	}
	
	public Role findById(Long roleId) throws NoSuchRoleException, SystemException {
		Role role = null;
		try{
			role = findOne(FIND_BY_ID, new RoleRowMapper(), roleId);
		}catch(Exception e) {
			throw processException(e);
		}
		if(role == null) {
			throw new NoSuchRoleException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + roleId);
		}
		return role;
	}

	public int findALLCount() throws SystemException {
		try{
			return findInt(FIND_ALL_COUNT);
		}catch(Exception e) {
			throw processException(e);
		}
	}
	
	public List<Role> findRoleList(int start, int offset) throws SystemException {
		try{
			return findList(FIND_ALL_LIMIT, new RoleRowMapper(), start, offset);
		}catch(Exception e) {
			throw processException(e);
		}
	}
	
}
